<?php
class AmazonComponent extends Object	{
	
	var $searchIndex = array('Blended', 'Books', 'Classical', 'DVD', 'Electronics', 'ForeignBooks', 'HealthPersonalCare', 
	'HomeGarden', 'Kitchen', 'Magazines', 'Music', 'MusicTracks', 'OutdoorLiving', 
	'PCHardware', 'Photo', 'Software', 'SoftwareVideoGames', 'Tools', 'VHS', 'Video', 'VideoGames', );
	
	var $name = 'Amazon'; 
	var $components = array('Session'); 
	var $options = array();
	
	function initialize(&$controller) {
		$this->controller = &$controller;
	}
	/**
	 * business as usual - set the options
	 * @param array $options
	 */
	function setOptions( $amazonId, $amazonSecretKey )	{
		if (!defined("AMAZON_APP_ID")) define('AMAZON_APP_ID',$amazonId);
		if (!defined("AMAZON_SECRET_ID")) define('AMAZON_SECRET_ID', $amazonSecretKey);
	}
		
	function request($params=array())	{
		$results = $this->amazonSignedRequest($params);
		App::import('Core', 'Xml');
		$xml = new Xml($results);
		$results = $xml->toArray();
		$results = $results['SimpleXMLElement'];
		return $results;
	}
	//t=amazonwebservice-21
	
	function saveinDB($results)	{
		$items = array();
		$this->controller->loadModel('Article');
		$searchIndex = '';
		if (isset($results['Items']['Request']['ItemSearchRequest']['SearchIndex']))
		$searchIndex = $results['Items']['Request']['ItemSearchRequest']['SearchIndex'];
		if (isset($results['Items']['Item']))
		foreach($results['Items']['Item'] as $i => $item)	{
			if (isset($item['OfferSummary']['LowestNewPrice']))	{
				$item = array('asin' => $item['ASIN'], 'searchindex' => $searchIndex, 'title' => $item['ItemAttributes']['Title'], 'price' => $item['OfferSummary']['LowestNewPrice']['FormattedPrice'], 'date' => time(), 'prettydate' => date('d.m.Y, H:i', time() ));
				$this->controller->Article->create();
				$this->controller->Article->save( array('Article' => $item) );
			}
		}
	}
	
	function search($keyword="", $params=array() )	{
		$params = array_merge(array('Operation' => 'ItemSearch', 'Condition' => 'All', 'Keywords' => $keyword, 'ResponseGroup' => 'Small'), $params);
		return $this->request( $params );
	}
	
	function itemLookup($asin="")	{
		$params = array('Operation' => 'ItemLookup', 'Condition' => 'All', 'IdType' => 'ASIN', 'ItemId' => $asin, 'ResponseGroup' => 'Large');
		return $this->request( $params );
	}
	
	function itemLookupPrice($asins=array())	{
		$params = array('Operation' => 'ItemLookup', 'Condition' => 'All', 'ItemId' => implode(',',$asins), 'ResponseGroup' => 'OfferSummary');
		return $this->request( $params );
	}
	
	function itemLookupResultToModel($product)	{
		/**
		 * TODO
		 * Eventuell gibt es keiner Bilder
		 * http://www.amazon.de/PlayStation-Konsole-Slim-Black-Starter/dp/B00411PQP8/ref=tpi_title_18?ie=UTF8&pf_rd_t=101&pf_rd_m=A3JWKAKR8XB7XF&pf_rd_p=211115391&pf_rd_s=center-3&pf_rd_r=1CHVRPMX3MDDKFAE31CP&pf_rd_i=700032
		 */
		$product = $product['Items']['Item'];
		$content = ''; if (isset($product['EditorialReviews']['EditorialReview']['Content'])) $content = $product['EditorialReviews']['EditorialReview']['Content'];
		$price = 0;
		if (isset($product['OfferSummary']['LowestNewPrice']['Amount'])) $price = $product['OfferSummary']['LowestNewPrice']['Amount'];
		if ($price == 0 && isset($product['OfferSummary']['LowestUsedPrice']['Amount'])) $price = $product['OfferSummary']['LowestUsedPrice']['Amount'];
		$product = array(
			'asin' => $product['ASIN'],
			'title' => $product['ItemAttributes']['Title'],
			'description' => $content,
			'short_description' => '',
			'detailurl' => $product['DetailPageURL'],
			'smallimage' => $product['SmallImage']['URL'],
			'mediumimage' => $product['MediumImage']['URL'],
			'largeimage' => $product['LargeImage']['URL'],
			'price' => $price,
			'observe' => 1,
			'next_price_update' => time() + 60 * 60,
		);
		return $product;
	}
		

	private function amazonSignedRequest($params) {
	    $method = "GET";
	    $host = "ecs.amazonaws.de";
	    $uri = "/onca/xml";
	    $params["Service"] = "AWSECommerceService";
	   # $params["AWSAccessKeyId"] = AMAZON_APP_ID;
	    $params["AssociateTag"] = "econ08-21";
	    $params["SubscriptionId"] = AMAZON_APP_ID;
	    $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
	    $params["Version"] = "2009-03-31";
	    ksort($params);
	    $canonicalized_query = array();
	    foreach ($params as $param=>$value) {
	        $param = str_replace("%7E", "~", rawurlencode($param));
	        $value = str_replace("%7E", "~", rawurlencode($value));
	        $canonicalized_query[] = $param."=".$value;
	    }
	    $canonicalized_query = implode("&", $canonicalized_query);
	    $string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;
	    $signature = base64_encode(hash_hmac("sha256", $string_to_sign, AMAZON_SECRET_ID, true));
	    $signature = str_replace("%7E", "~", rawurlencode($signature));
	    $request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature;
	    App::import('Core', 'HttpSocket');
		$HttpSocket = new HttpSocket();
		$response = $HttpSocket->get($request);
	    if ($response === false)
	        return false;
	    else {
	        $pxml = simplexml_load_string($response);
	        if ($pxml === false) return false;
	        else return $pxml;
	    }
	}
}